package com.hddznet.uniplatform.sm.util;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;

import com.google.gson.Gson;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class HdHttpUtils {

	/**
	 * 发送POST请求
	 * 
	 * @param url  请求url
	 * @param data 请求数据
	 * @return 结果
	 */
	public static String doPost(String url, String data, Header header) {
		log.info("url={}", url);
		log.info("data={}", data);
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpPost httpPost = new HttpPost(url);
		RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(20000)
				.setConnectionRequestTimeout(10000).build();
		httpPost.setConfig(requestConfig);
		String context = StringUtils.EMPTY;
		if (!StringUtils.isEmpty(data)) {
			StringEntity body = new StringEntity(data, "UTF-8");
			httpPost.setEntity(body);
		}
		// 设置回调接口接收的消息头
		httpPost.setHeader(header);
		CloseableHttpResponse response = null;
		try {
			response = httpClient.execute(httpPost);
			HttpEntity entity = response.getEntity();
			context = EntityUtils.toString(entity, "UTF-8");
			log.info("context={}", context);
		} catch (Exception e) {
			log.error("执行post接口异常", e);
		} finally {
			try {
				response.close();
				httpPost.abort();
				httpClient.close();
			} catch (Exception e) {
			}
		}
		return context;
	}
	
	public static void main(String[] args) {
		String url = "http://192.168.100.188:7009/hdl/oauth/v1.0/access.json";
		Map<String, String> params = new HashMap<>();
		params.put("grant_type", "authorization_code");
		params.put("client_id", "5eb5437f115916000a0284a1");
		params.put("client_secret", "f40dfdfa3f68c1f49a005010f6e47bedc4705573c36bd1168709e435880525e0");
		params.put("redirect_uri", "http://127.0.0.1:8066/safetyManagement/cas/client/auth");
		params.put("code", "aG-5dt1rSJ-OZSPjBO_FNA");
		Gson gson = new Gson();
		Header header = new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json");
		
		HdHttpUtils.doPost(url, gson.toJson(params), header);
	}
}
